package com.rong.distributed.transaction.mq;

import java.util.UUID;

import com.rong.distributed.transaction.mq.bean.Message;
import com.rong.distributed.transaction.mq.constants.MessageStatus;
import com.rong.distributed.transaction.mq.constants.TransactionStatus;

/**
 * 消息投递服务
 * 
 * @author liurong
 *
 */
public class MessageDispathcer {
	private static MessageStore messageStore = MessageStore.getInstance();
	private static MessageQueue messageQueue = MessageQueue.getInstance();

	/**
	 * 接收半消息
	 * 
	 * @param message
	 * @return
	 */
	public String recvHalfMessage(Message message) {
		String messageId = UUID.randomUUID().toString();
		message.setId(messageId);
		message.setStatus(MessageStatus.HALF_MESSAGE.getStatus());
		messageStore.putMessage(message);
		return messageId;
	}

	/**
	 * 处理半消息
	 * 
	 * @param messageId
	 * @param tranactionStatus
	 * @return
	 */
	public String handleHalfMessage(String messageId, Integer tranactionStatus) {
		Message message = messageStore.removeMessage(messageId);
		message.setStatus(MessageStatus.COMPLETE_MESSAGE.getStatus());
		String ack = "ok";
		if (TransactionStatus.COMMIT.getStatus().equals(tranactionStatus)) {
			messageQueue.putMessage(message);
			return ack;
		}
		if (TransactionStatus.ROLLBACK.getStatus().equals(tranactionStatus)) {
			System.out.println("mq:丢弃消息" + message);
			return ack;
		}

		return ack;
	}

	public static void main(String[] args) {
		System.out.println(UUID.randomUUID().toString());
	}
}
